package net.wofly.common.condition;

import lombok.Data;
import net.wofly.common.json.JSONFilter;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * 条件表达式
 * @version V1.0
 */
@Data
public class Condition {

	/**
	 * 过滤条件
	 */
	private List<FilterCondition> filterCondition;
	/**
	 * 排序条件
	 */
	private List<OrderCondition> orderConditions;

	/**
	 * jpa的排序条件
	 */
	@JSONFilter
	private Sort sort;
	/**
	 * jpa的查询条件
	 */
	@JSONFilter
	private Specification specification;

	public Condition() {
	}

	public void addLastFilter(FilterCondition fc) {
		this.addFilter(fc, 1);
	}

	public void addFirstFilter(FilterCondition fc) {
		this.addFilter(fc, -1);
	}

	private void addFilter(FilterCondition fc, int direct) {
		if (CollectionUtils.isEmpty(this.filterCondition)) {
			this.filterCondition = new LinkedList<FilterCondition>();
			fc.setSortNo(1);
		} else {
			int destNo = 0;
			FilterCondition destFc = null;
			int pos = 0;
			for (FilterCondition temp : this.filterCondition) {
				if(pos==0){
					destFc = temp;
				}else{
					if (direct > 0) {
						if (temp.getSortNo() > destNo) {
							destNo = temp.getSortNo();
							destFc = temp;
						}
					} else {
						if (temp.getSortNo() < destNo) {
							destNo = temp.getSortNo();
							destFc = temp;
						}
					}
				}
				pos++;
			}
			if(direct<=0){
				destFc.setConditionRelate(fc.getConditionRelate());
			}
			fc.setSortNo(destNo + direct);
		}
		this.filterCondition.add(fc);
	}

	public void addLastOrder(OrderCondition oc) {
		this.addOrder(oc, 1);
	}

	public void addFirstOrder(OrderCondition oc) {
		this.addOrder(oc, -1);
	}

	private void addOrder(OrderCondition oc, int direct) {
		if (CollectionUtils.isEmpty(this.orderConditions)) {
			this.orderConditions = new LinkedList<OrderCondition>();
			oc.setSortNo(1);
		} else {
			int destNo = 0;
			for (OrderCondition temp : this.orderConditions) {
				if (direct > 0) {
					if (temp.getSortNo() > destNo) {
						destNo = temp.getSortNo();
					}
				} else {
					if (temp.getSortNo() < destNo) {
						destNo = temp.getSortNo();
					}
				}
			}
			oc.setSortNo(destNo + 1);
		}
		this.orderConditions.add(oc);
	}
}